package com.twu.biblioteca.dao.memory;

import com.google.common.collect.Lists;

import com.twu.biblioteca.dao.MovieDao;
import com.twu.biblioteca.entity.Movie;
import com.twu.biblioteca.exception.DaoNotFoundException;
import com.twu.biblioteca.util.Predicate;

import java.util.List;

public class MemoryMovieDao extends MemoryBaseDao<Movie> implements MovieDao {

  public MemoryMovieDao() {
    List<Movie> movieList = Lists.newArrayList();

    Movie movie1 = new Movie("10.123/1234-5678-9ABC-DEF0-K", "Avengers", "Joss Whedon");
    movie1.setYear(2012);
    movie1.setRate(10);

    Movie movie2 = new Movie("10.123/1234-5671-9ABC-DEF0-K", "Mission: Impossible - Ghost Protocol",
        "Brad Bird");
    movie2.setYear(2011);
    movie2.setRate(8);

    Movie movie3 = new Movie("10.123/1234-5672-9ABC-DEF0-K", "Fast & Furious 6", "Justin Lin");
    movie3.setYear(2013);
    movie3.setRate(6);

    Movie movie4 = new Movie("10.123/1234-5673-9ABC-DEF0-K", "Captain America: The Winter Soldier",
        "Anthony Russo");
    movie4.setYear(2014);
    movie4.setRate(10);

    Movie movie5 = new Movie("10.123/1234-5674-9ABC-DEF0-K", "Iron Man 3", "Shane Black");
    movie5.setYear(2013);
    movie5.setRate(9);

    movieList.add(movie1);
    movieList.add(movie2);
    movieList.add(movie3);
    movieList.add(movie4);
    movieList.add(movie5);

    super.setItemList(movieList);
  }

  @Override
  public Movie findByTitle(String title) {
    return memoryMovieDaoTemplate(new Predicate<Movie, String>() {
      public boolean isTrue(Movie movie, String title) {
        return movie.getTitle().equals(title);
      }
    }, title);
  }

  @Override
  public Movie findByEidr(final String eidr) {
    return memoryMovieDaoTemplate(new Predicate<Movie, String>() {
      public boolean isTrue(Movie movie, String title) {
        return movie.getEidr().equals(eidr);
      }
    }, eidr);
  }

  @Override
  public List<Movie> getAvailableMovies() {
    List<Movie> availableMovies = Lists.newArrayList();
    for (Movie m : itemList) {
      if (m.isAvailable())
        availableMovies.add(m.getMovie(m));
    }
    return availableMovies;
  }

  @Override
  public List<Movie> getCheckoutMovies() {
    List<Movie> checkoutMovies = Lists.newArrayList();
    for (Movie m : itemList) {
      if (!m.isAvailable())
        checkoutMovies.add(m.getMovie(m));
    }
    return checkoutMovies;
  }

  private Movie memoryMovieDaoTemplate(Predicate predicate, Object obj) {
    for (Movie m : itemList) {
      if (predicate.isTrue(m, obj))
        return m;
    }
    throw new DaoNotFoundException("No movie found with the given ID");
  }
}
